/**
 * Created by pzw on 2015/4/1.
 */
var expressionListTable = function () {

    var dataTable;
    var $table = $("#dataTable");

    /**
     * dataTable事件初始化方法
     */
    var handleRecords = function () {
        dataTable = new Datatable();
        dataTable.init({
            src: $table,
            onQuery: function (data) {
                data.formulaName = $("#formulaNameQuery").val().trim();
                data.formulaDescription = $("#descriptionQuery").val().trim();
            },
            onSortColumn: function (sortColumn, sortDirection) {
                switch (sortColumn) {
                    case "formulaName":
                        sortColumn = "formula_name";
                        break;
                    case "formulaDescription":
                        sortColumn = "formula_description";
                        break;
                }
                return customGlobal.onSortColumnDefault(sortColumn, sortDirection);
            },
            dataTable: {
                "ajax": {
                    "url": basePath + "admin/formal/getFormulaListPage"
                },
                "columns": [
                    {data: 'formulaName', orderable: true, searchable: true},
                    {data: 'formulaDescription', orderable: true, searchable: true},
                    {data: 'memo', orderable: true, searchable: true},
                    {
                        data: 'formulaType', orderable: false, searchable: true,
                        render: function (data, type, full) {
                            return full.formulaType.name;
                        }
                    },
                    {
                        data: 'category', orderable: true,
                        render: function (data, type, full) {
                            var category = full.category;
                            switch (category) {
                                case 1:
                                    return "输入";
                                case 2:
                                    return "输出";
                                case 3:
                                    return "输入&输出";
                                case 4:
                                    return "中间值";
                                case 0:
                                    return "其他";
                                default :
                                    return "";
                            }
                        }
                    },
                    {
                        data: 'operate', orderable: false,
                        render: function (data, type, full) {
                            return '<a class="edit btn default btn-xs purple" id="' + full.id + '"><i class="fa fa-edit"></i>' + i18n['edit'] + '</a>&nbsp;'
                                + '<a class="delete btn default btn-xs black" data-target="#confirmDialog" data-toggle="modal"><i class="fa fa-times"></i>' + i18n["delete"] + '</a>&nbsp;';
                        }
                    }
                ]
            }
        });
    };

    var handleEvent = function () {
        var oldFormalName = "";

        var validateOption = {
            rules: {
                formulaName: {
                    required: true,
                    remote: {
                        url: "admin/formal/checkRepeatFormulaName",
                        type: "post",
                        data: {
                            formulaName: function () {
                                return $("#formulaName").val();
                            },
                            memo: function () {
                                return oldFormalName;
                            }
                        }
                    }
                },
                formulaDescription: {
                    required: true
                },
                memo: {
                    required: true
                },
                formulaType: {
                    required: true
                }
            },
            messages: {
                formulaName: {
                    required: "公式名称不能为空！",
                    remote: "公式名称已存在！"
                },
                formulaDescription: {
                    required: "公式内容不能为空！"
                },
                memo: {
                    required: "公式描述不能为空！"
                },
                formulaType: {
                    required: "公式类型不能为空！"
                }
            }
        };

        $("#addFormula").on("click", function () {
            oldFormalName = "";
            $("#modalTitle").html(i18n["addFormula"]);
            customGlobal.clearFormAndShowDialog("modalDialog");
            $("#dialogForm").validate(validateOption).resetForm();
            $("#addBtn").show();
            $("#updateBtn").hide();
            $("formulaName").on("blur", function () {
                $("#dialogForm").validate();
            })
        });


        $("#addBtn").on("click", function () {
            if ($("#dialogForm").validate().form()) {
                customGlobal.blockUI("#modalContent");
                var formulaType = {
                    id: $("#formulaType").getGAutoHiddenValue()
                };
                $.ajax({
                    url: "admin/formal",
                    data: JSON.stringify({
                        formulaName: $("#formulaName").val(),
                        memo: $("#memo").val(),
                        category: $("#category").val(),
                        formulaDescription: $("#formulaDescription").val().trim(),
                        formulaType: formulaType
                    }),
                    contentType: "application/json; charset=utf-8",
                    type: "post",
                    success: function (data) {
                        if (customGlobal.ajaxCallback(data)) {
                            $("#modalDialog").modal("hide");
                            dataTable.reloadTable();
                        }
                    }
                });
            }
        });

        $table.on("click", "a.edit", function () {
            $("#modalTitle").html(i18n['editFormula']);
            customGlobal.clearFormAndShowDialog("modalDialog");
            $("#dialogForm").validate(validateOption).resetForm();
            $("#addBtn").hide();
            $("#updateBtn").show();
            $.get("admin/formal/" + $(this).attr("id"), function (data) {
                var formula = data.returnData.formula;
                $("#id").val(formula.id);
                $("#formulaName").val(formula.formulaName);
                $("#memo").val(formula.memo);
                $("#category").val(formula.category);
                $("#formulaDescription").val(formula.formulaDescription);
                $("#formulaType").val(formula.formulaType.name).setGAutoHiddenValue(formula.formulaType.id);
                oldFormalName = formula.formulaName;
            });

        });

        $("#updateBtn").on("click", function () {
            if ($("#dialogForm").validate().form()) {
                customGlobal.blockUI("#modalContent");
                var data = {
                    id: $("#id").val(),
                    formulaName: $("#formulaName").val(),
                    memo: $("#memo").val(),
                    category: $("#category").val(),
                    formulaDescription: $("#formulaDescription").val(),
                    formulaType: {
                        id: $("#formulaType").getGAutoHiddenValue()
                    }
                };
                $.ajax({
                    url: "admin/formal",
                    data: JSON.stringify(data),
                    type: "put",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        if (customGlobal.ajaxCallback(data)) {
                            $("#modalDialog").modal("hide");
                            dataTable.reloadTable();
                        }
                    }
                });
            }
        });

        $table.on("click", "a.delete", function () {
            var $this = $(this);
            //confirm中确认按钮事件，此处需要unbind，否则点击取消时下次再点击删除按钮会重复绑定click。
            $("#confirmBtn").off("click.deleteRow").on("click.deleteRow", function () {
                $.ajax({
                    url: "admin/formal/" + $table.DataTable().row($this.parents('tr')[0]).data().id,
                    dataType: "json",
                    type: "DELETE",
                    success: function (data) {
                        $("#confirmDialog").modal("hide");
                        if (customGlobal.ajaxCallback(data)) {
                            dataTable.reloadTable();
                        }
                    }
                })
            })
        });

        $("#formulaType,#typeQuery").select2({
            placeholder: "请选择一个公式类型",
            allowClear: true
        })
    };

    return {
        init: function () {
            handleRecords();
            handleEvent();
        }
    };
}();
